<template>
	<view class="uni-container">
		<uni-row>
			<uni-col :span="14">
				<uni-forms ref="form" :model="formData" validateTrigger="bind">
					<uni-forms-item name="user_id" label="">
						<uni-easyinput placeholder="关联用户ID" v-model="formData.user_id" v-if="$hasRole('admin')"
							:disabled=true></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item name="company_name" label="企业名称" required label-width="200rpx">
						<uni-easyinput v-model="formData.company_name" :focus="isFocus" trim="both"
							:disabled="isPending() || isApproved()"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item name="business_license" label="营业执照" required label-width="200rpx">
						<uni-file-picker file-mediatype="image" return-type="object" v-model="formData.business_license"
							:del-icon="isEdit"></uni-file-picker>
					</uni-forms-item>
					<!-- 新增的法人身份证（国徽面） -->
					<uni-forms-item name="legal_person_idcard_national" label="法人身份证（国徽面）" required
						label-width="200rpx">
						<uni-file-picker file-mediatype="image" return-type="object" limit="1"
							v-model="formData.legal_person_idcard_national" :del-icon="isEdit"></uni-file-picker>
					</uni-forms-item>
					<!-- 新增的法人身份证（头像面） -->
					<uni-forms-item name="legal_person_idcard_portrait" label="法人身份证（头像面）" required
						label-width="200rpx">
						<uni-file-picker file-mediatype="image" return-type="object" limit="1"
							v-model="formData.legal_person_idcard_portrait" :del-icon="isEdit"></uni-file-picker>
					</uni-forms-item>
					<uni-forms-item name="contact_info" label="手机号码" required label-width="200rpx">
						<uni-easyinput v-model="formData.contact_info" trim="both" type="number"
							:disabled="!isEdit"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item name="submit_time" label="提交时间" label-width="200rpx" v-if="$hasRole('admin')">
						<uni-datetime-picker return-type="timestamp"
							v-model="formData.submit_time"></uni-datetime-picker>
					</uni-forms-item>
					<uni-forms-item name="audit_time" label="审核时间" label-width="200rpx" v-if="$hasRole('admin')">
						<uni-datetime-picker return-type="timestamp"
							v-model="formData.audit_time"></uni-datetime-picker>
					</uni-forms-item>
					<uni-forms-item name="audit_remark" label="审核备注" label-width="200rpx">
						<uni-easyinput v-model="formData.audit_remark" trim="both"></uni-easyinput>
					</uni-forms-item>
					<view class="uni-button-group">
						<button type="primary" class="uni-button" style="width: 100px;" @click="submit"
							:disabled="$hasRole('admin') || !isEdit">提交</button>
						<navigator open-type="navigateBack" style="margin-left: 15px;">
							<button class="uni-button" style="width: 100px;">返回</button>
						</navigator>
					</view>
				</uni-forms>
			</uni-col>
			<uni-col :span="10" v-if="!$hasRole('admin')">
				<uni-forms ref="form" :model="formData" validateTrigger="bind">
					<uni-forms-item name="auth_status" label="认证状态" label-width="200rpx"
						v-if="formData.auth_status != ''">
						<uni-steps style="height: 200px;" :options="statusList" direction="column"
							:active="active"></uni-steps>
					</uni-forms-item>
				</uni-forms>
			</uni-col>
		</uni-row>
	</view>
</template>

<script>
import { validator } from '@/js_sdk/validator/merchant-auth.js';
import { PENDING, APPROVED, REJECTED } from '@/utils/constants.js'

const db = uniCloud.database();
const dbCollectionName = 'merchant-auth';
const merchantAuthApi = uniCloud.importObject('merchant-auth-api');

function getValidator(fields) {
	let result = {}
	for (let key in validator) {
		if (fields.includes(key)) {
			result[key] = validator[key]
		}
	}
	return result
}

export default {
	data() {
		let formData = {
			"user_id": "",
			"company_name": "",
			"business_license": null,
			"legal_person_idcard_national": null, // 新增字段
			"legal_person_idcard_portrait": null, // 新增字段
			"auth_status": '',
			"submit_time": null,
			"audit_time": null,
			"audit_remark": "",
			"contact_info": "",
			"extra_files": []
		}
		return {
			isFocus: true,
			isEdit: false,
			formData,
			formOptions: {
				"auth_status_localdata": [{
					"value": "pending",
					"text": "审核中"
				},
				{
					"value": "approved",
					"text": "通过"
				},
				{
					"value": "rejected",
					"text": "未通过"
				}
				]
			},
			rules: {
				...getValidator(Object.keys(formData))
			},
			statusList: [
				{ title: '未提交' },
				{ title: '审核中' },
				{ title: '审核通过' },
				{ title: '审核未通过' }
			],
			active: 0
		}
	},
	async onLoad() {
		this.formData.user_id = uniCloud.getCurrentUserInfo().uid

		/**
		 * 查询当前用户是否已经提交过认证
		 */
		const { success, errCode, result } = await db.collection(dbCollectionName).where({
			user_id: this.formData.user_id
		}).get();

		if (success && errCode === 0 && result.data.length > 0) {
			this.formData = result.data[0]
			// 如果没有auth_status,设置状态为pending。否则设置为数据库的返回值
			this.formData.auth_status = result.data[0].auth_status || PENDING
		}

		if (this.formData.auth_status === PENDING) {
			this.active = 1
		} else if (this.formData.auth_status === APPROVED) {
			this.active = 2
		} else if (this.formData.auth_status === REJECTED) {
			this.active = 3
		}

		this.isEdit = this.canEdit()
	},
	onReady() {
		this.$refs.form.setRules(this.rules)
	},
	methods: {
		/**
		 * 是否可以更改
		 * 如果状态是 pending 或者 rejected，那么就不能更改了。
		 */
		canEdit() {
			return this.isPending() ? false : this.isApproved() ? false : true
		},

		/**
		 * 当前状态正在审核中
		 */
		isPending() {
			return this.formData.auth_status === PENDING
		},

		/**
		 * 当前状态审核通过
		 */
		isApproved() {
			return this.formData.auth_status === APPROVED
		},

		/**
		 * 当前状态审核未通过
		 */
		isRejected() {
			return this.formData.auth_status === REJECTED
		},

		/**
		 * 验证表单并提交
		 */
		submit() {
			uni.showLoading({
				mask: true
			})
			this.$refs.form.validate().then((res) => {
				return this.submitForm({
					...res,
					user_id: this.formData.user_id
				})
			}).catch(() => { }).finally(() => {
				uni.hideLoading()
			})
		},

		/**
		 * 提交表单
		 */
		submitForm(value) {
			if (!value.submit_time) {
				delete value.submit_time
			}

			// 这里设置为，提交到某个云对象
			return merchantAuthApi.updateByCustomer(value).then(res => {
				const { code } = res

				if (code === 0) {
					//
					uni.showToast({
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}
				else if (code === 500) {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}
			})
		}
	}
}
</script>